import {
  useState,
  useRef,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from "react";
import {
  FaMicrophone,
  FaKeyboard,
  FaSmile,
  FaPlusCircle,
  FaPaperPlane,
} from "react-icons/fa";
import EmojiCard from "./EmojiCard";
import PlusCard from "./PlusCard";

interface InputBarProps {
  onSendMessage: (message: string) => void;
  onHeightChange: (height: number) => void;
}

const InputBar = forwardRef<HTMLDivElement, InputBarProps>(
  ({ onSendMessage, onHeightChange }, ref) => {
    const [isVoiceMode, setIsVoiceMode] = useState(false);
    const [isEmojiCardOpen, setIsEmojiCardOpen] = useState(false);
    const [isPlusCardOpen, setIsPlusCardOpen] = useState(false);
    const [message, setMessage] = useState("");
    const containerRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);

    useImperativeHandle(ref, () => containerRef.current as HTMLDivElement);

    useEffect(() => {
      if (containerRef.current && onHeightChange) {
        const height = containerRef.current.offsetHeight;
        onHeightChange(height);
      }
    }, [isVoiceMode, isEmojiCardOpen, isPlusCardOpen, message, onHeightChange]);

    const handleEmojiSelect = (emoji: string) => {
      setMessage((prev) => prev + emoji);
    };

    const handleSendMessage = () => {
      if (message.trim()) {
        onSendMessage(message);
        setMessage("");
        setIsEmojiCardOpen(false);
        setIsPlusCardOpen(false);
      }
    };

    useEffect(() => {
      if (isEmojiCardOpen && inputRef.current) {
        const timer = setTimeout(() => {
          inputRef.current?.focus();
        }, 100);

        return () => clearTimeout(timer);
      }
    }, [isEmojiCardOpen]);

    const toggleVoiceMode = () => {
      setIsVoiceMode(!isVoiceMode);
      setIsEmojiCardOpen(false);
      setIsPlusCardOpen(false);
    };

    const toggleEmojiCard = () => {
      setIsEmojiCardOpen(!isEmojiCardOpen);
      setIsPlusCardOpen(false);
    };

    const togglePlusCard = () => {
      setIsPlusCardOpen(!isPlusCardOpen);
      setIsEmojiCardOpen(false);
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
      if (e.key === "Enter") {
        handleSendMessage();
      }
    };

    useEffect(() => {
      const handleClickOutside = (e: MouseEvent) => {
        const target = e.target as HTMLElement;
        if (
          !target.closest(".emoji-card-container") &&
          !target.closest(".plus-card-container") &&
          !target.closest(".input-controls")
        ) {
          setIsEmojiCardOpen(false);
          setIsPlusCardOpen(false);
        }
      };

      document.addEventListener("click", handleClickOutside);
      return () => document.removeEventListener("click", handleClickOutside);
    }, []);

    return (
      <div
        ref={containerRef}
        className="w-full bg-white transition-[height] duration-300 ease-in-out"
      >
        <div className="input-controls p-2 flex items-center border-t border-gray-200">
          <button
            className="btn btn-ghost btn-circle text-xl"
            onClick={toggleVoiceMode}
          >
            {isVoiceMode ? <FaKeyboard /> : <FaMicrophone />}
          </button>

          {isVoiceMode ? (
            <button className="flex-1 mx-2 py-3 bg-gray-200 rounded-full text-center">
              按住 说话
            </button>
          ) : (
            <div className="flex-1 flex items-center bg-gray-100 rounded-full mx-2">
              <input
                ref={inputRef}
                type="text"
                className="flex-1 py-3 px-4 bg-transparent outline-none"
                placeholder="输入消息..."
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                onKeyPress={handleKeyPress}
                onClick={() => {
                  setIsEmojiCardOpen(false);
                  setIsPlusCardOpen(false);
                }}
              />
            </div>
          )}

          {!message && (
            <button
              className={`btn btn-ghost btn-circle text-xl ${
                isEmojiCardOpen ? "text-blue-500" : ""
              }`}
              onClick={toggleEmojiCard}
            >
              <FaSmile />
            </button>
          )}

          {!message && (
            <button
              className={`btn btn-ghost btn-circle text-xl ${
                isPlusCardOpen ? "text-blue-500" : ""
              }`}
              onClick={togglePlusCard}
            >
              <FaPlusCircle />
            </button>
          )}

          {(message || isEmojiCardOpen) && (
            <button
              className="btn btn-ghost btn-circle text-xl"
              onClick={handleSendMessage}
            >
              <FaPaperPlane className="text-blue-500" />
            </button>
          )}
        </div>

        <div
          className={`emoji-card-container transition-all duration-300 overflow-hidden ${
            isEmojiCardOpen ? "max-h-60 opacity-100" : "max-h-0 opacity-0"
          }`}
        >
          {isEmojiCardOpen && (
            <EmojiCard
              onSelect={handleEmojiSelect}
              onSend={handleSendMessage}
            />
          )}
        </div>

        <div
          className={`plus-card-container transition-all duration-300 overflow-hidden ${
            isPlusCardOpen ? "max-h-60 opacity-100" : "max-h-0 opacity-0"
          }`}
        >
          {isPlusCardOpen && <PlusCard />}
        </div>
      </div>
    );
  }
);

export default InputBar;
